package com.yin.jia.liang.controller;

import com.yin.jia.liang.entity.*;
import com.yin.jia.liang.service.ContactService;
import com.yin.jia.liang.vo.GoodsOrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("contact")
public class ContactController {

    @Autowired
    ContactService contactService;

    @RequestMapping(value = "list", method = RequestMethod.GET)
    public String list(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/login";
        }
        List<Contact> contacts = null;
        if ("admin".equals(user.getUsername())) {
            contacts = contactService.find();
        } else {
            contacts = contactService.findByUserId(user.getId());
        }
        model.addAttribute("contacts", contacts);
        return "contact/list";
    }

    @RequestMapping(value = "add", method = RequestMethod.POST)
    public String index(@ModelAttribute Contact contact, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/login";
        }
        contact.setUserId(user.getId());
        contactService.save(contact);
        return "redirect:/us";
    }

    @RequestMapping(value = "del/{id}", method = RequestMethod.GET)
    public String del(@PathVariable Integer id, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/login";
        }
        if ("admin".equals(user.getUsername())) {
            contactService.delete(id);
        }
        return "redirect:/contact/list";
    }
}
